//封装购物车模块
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './user.js'
import { addCartAPI, getCartListAPI, delCartAPI } from '@/api/index.js'
export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  //1、定义管理数据用户的state-cartList
  const cartList = ref([])
  //获取购物车列表方法
  const getCartList = async () => {
    const res = await getCartListAPI()
    cartList.value = res.data.result
  }
  //2、定义获取接口数据的action函数
  const addCart = async (goods) => {
    const { skuId, count } = goods
    if (isLogin.value) {
      //登录之和的加入购物车逻辑
      await addCartAPI({ skuId, count })
      getCartList()
    } else {
      //添加购物车操作
      //已添加过- count+1
      //未添加过-push
      //思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        //找到了
        item.count++
      } else {
        //没找到
        cartList.value.push(goods)
      }
    }

  }
  //定义删除购物车函数
  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      getCartList()
    } else {
      //思路：1、找到要删除项的下标值->splice
      //2、使用数组过滤方法  -> filter
      // const idx = cartList.value.find((item) => skuId === item.skuId)
      // cartList.value.splice(idx, 1)
      cartList.value = cartList.value.filter((item) => skuId !== item.skuId)
    }
  }
  //清除购物车
  const clearCart = () => {
    cartList.value = []
  }
  //定义计算属性
  //1、购物车商品总数量---所有项count的之和
  const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
  //2、购物车商品总价格
  const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
  //3、是否全选
  const isAll = computed(() => cartList.value.every((item) => item.selected))
  //4、列表购物车已选择的商品总数量
  const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
  //5、列表购物车已选择的商品总价格
  const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))

  //定义单选功能
  const singleCheck = (skuId, selected) => {
    //通过skuId找到要修改的那一项，然后把它的selected修改为我们传过来的skuId
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = selected
  }
  //全选功能
  const allCheck = (selected) => {
    //把cartList的每一项selected都设置为全选状态
    cartList.value.forEach(item => item.selected = selected)
  }
  //3、以对象的格式把state个action return
  return {
    cartList, addCart, delCart, allCount, allPrice, singleCheck, isAll, allCheck, selectedCount, selectedPrice, clearCart, getCartList
  }
  //使用持久化插件配置
}, {
  persist: true,
})